﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Management.Smo;

namespace QuizzAdminData
{
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    /// <author>Kenny Vaneetvelde</author>
    public static class DBMaintenance
    {
        /// <summary>
        /// Backup DB naar file
        /// </summary>
        /// <author>Kenny Vaneetvelde</author>
        public static void BackupDB(string backupFile)
        {
            try
            {
                Server localServer = new Server();
                Backup backupMgr = new Backup();
                backupMgr.Devices.AddDevice(backupFile, DeviceType.File);
                backupMgr.Database = "QuizzDB";
                backupMgr.Action = BackupActionType.Database;
                backupMgr.SqlBackup(localServer);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Restore DB van file
        /// </summary>
        /// <author>Kenny Vaneetvelde</author>
        public static void RestoreDB(string backupFile)
        {
            SqlConnection conn = QuizAdminDB.GetConnection();
            SqlCommand sqlDBrestoreCommand = new SqlCommand();

            try
            {
                conn.Open();
                sqlDBrestoreCommand.Connection = conn;
                sqlDBrestoreCommand.CommandText = "Use Master";
                sqlDBrestoreCommand.ExecuteNonQuery();
                sqlDBrestoreCommand.CommandText = "ALTER DATABASE QuizzDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
                sqlDBrestoreCommand.ExecuteNonQuery();
                sqlDBrestoreCommand.CommandText = "RESTORE DATABASE QuizzDB FROM DISK = '" + backupFile + "';";
                sqlDBrestoreCommand.ExecuteNonQuery();
                sqlDBrestoreCommand.CommandText = "Use Master";
                sqlDBrestoreCommand.ExecuteNonQuery();
                sqlDBrestoreCommand.CommandText = "ALTER DATABASE QuizzDB SET MULTI_USER;";
                sqlDBrestoreCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }

        }
    }
}
